<?php
/**
 * Created by PhpStorm.
 * User: liuwei
 * Date: 2022/12/15
 * Time: 18:40
 */

namespace App\Http\Controllers\Api;

use App\Services\Business\Models\Favorite;
use App\Services\Member\Models\FavoriteCategory;

use Illuminate\Http\Request;
use App\Http\Requests\ApiV2\FavoriteCategoryRequest;
class FavoriteCategoryController extends BaseController
{


    public function detail(Request $request,$categoryId)
    {

        $resourceType = $request->input('resourceType', '');
        $size = $request->input('size', 20);
        $favorites = Favorite::query()
            ->where('user_id', $this->id())
            ->when($categoryId, function ($query) use ($categoryId) {
                return $query->where('category_id', $categoryId);
            })
            ->when($resourceType, function ($query) use ($resourceType) {
                return $query->where('favorable_type', 'App\Services\Business\Models\\'.ucfirst($resourceType));
            })
            ->orderByDesc('created_at')
            ->paginate($size);

        $serviceName = 'App\Services\Business\Services\\'.ucfirst($resourceType).'Service';
        $resourceService= app()->make($serviceName);
        $favorites  = $resourceService->getList(array_column($favorites->items(),'favorable_id'));
        return $this->successData(compact('favorites'));

    }
    public function edit($id)
    {

        try {
            $category = FavoriteCategory::query()->where('id', $id)->firstOrFail();
        } catch (\Exception $exception) {
            return $this->error("操作不成功");
        }

        return $this->successData(compact('category'));
    }

    /**
     * 收藏
     *
     * @param FavoriteCategoryRequest $request
     * @param FavoriteCategory $category
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(FavoriteCategoryRequest $request, FavoriteCategory $category)
    {

        $category->fill($request->filldata())->save();

        return $this->success("成功");
    }

    /**
     * 更新
     * @param $id
     * @param FavoriteCategoryRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update( FavoriteCategoryRequest $request,$id)
    {
        $collect = FavoriteCategory::query()->where('id', $id)->firstOrFail();
        $collect->fill($request->filldata())->save();
        return $this->success("更新成功");
    }

    /**
     * 删除
     * @param $id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete($id)
    {

        $collect = FavoriteCategory::query()->where('id', $id)->firstOrFail();
        if ($collect->resources()->exists()) {
            return $this->error(__('当前分类收藏了课程'));
        }
        $collect->delete();
        return $this->success("成功");
    }

}